import React, { useCallback, useMemo, useState } from 'react'
export default function App() {
    const [list,setlist] = useState([{
        id:0,
        price: 35,
        pic:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg10.360buyimg.com%2Fn0%2Fs800x1026_jfs%2Ft1%2F148212%2F10%2F19181%2F129845%2F60a625e7Ebefe3dfb%2F51140e735001b872.jpg%21cc_800x1026.jpg&refer=http%3A%2F%2Fimg10.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656600329&t=17add687292236a351595a864b6bdc81',
        name:'商品1',
        amount:1
    },{
        id:1,
        price: 78,
        pic:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimgservice.suning.cn%2Fuimg1%2Fb2c%2Fimage%2FLM22oAUH_x3Bp_TKjkoN_A.jpg_800w_800h_4e&refer=http%3A%2F%2Fimgservice.suning.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656601124&t=f77e67d12d03b6037a95463230be2530',
        name:'商品2',
        amount:1
    },{
        id:2,
        price: 123,
        pic:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg14.360buyimg.com%2Fn1%2Fs350x449_jfs%2Ft1%2F136859%2F23%2F9506%2F123040%2F5f58cd66Eb36a5cb5%2Fbfe669a5f9e80f89.jpg%21cc_350x449.jpg&refer=http%3A%2F%2Fimg14.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656601124&t=a56ec9beac4ac63614702629eed9f021',
        name:'商品3',
        amount:1
    }]);
    const comTotal = useMemo(()=>{  //计算总价
        var total = 0;
        list.forEach(item => {
            total+=item.price*item.amount;
        })
        return total;
    },[list])
    let deAmount = useCallback((index) =>{   //控制商品数量减少
        var newlist = [...list];
        if(newlist[index].amount>1)
            newlist[index].amount--;
        
        setlist(newlist);
    },[list])
    let addAmount = useCallback((index) =>{  //控制商品数量增加
        var newlist = [...list];
            newlist[index].amount++;
        setlist(newlist);
    },[list])
  return (
    <div>
        {list.map((item, index) =>
            <div key={item.id} style={{ margin:'1px 0', display:'flex',justifyContent:'space-around', alignItems:'center'}}>
                <img src={item.pic} alt='' style={{width: '100px', height:'130px'}}></img>
                <div style={{width:'120px', display:'flex', flexDirection:'column', justifyContent:'center',alignItems:'center'}}>
                    <div>{item.name}</div>
                    <div>￥{item.price}</div>
                </div>
                <div style={{display:'flex'}}>
                    <button onClick={()=>deAmount(index)}>-</button>
                    <span style={{width:"20px",textAlign:'center'}}>{item.amount}</span>
                    <button onClick={()=>addAmount(index)}>+</button>
                </div>
            </div>)}
            <div style={{textAlign:'right'}}>共计{comTotal}元</div>
    </div>
  )
}
